//
//  BKUser.m
//  XPhoto
//
//  Created by baboy on 2019/6/26.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKUser.h"
#import "Mem.h"
#import "NSString+x.h"
#import "DBCache.h"
#import "NSDictionary+x.h"

#define MEM_USER_KEY @"current_user"
#define MEM_AUTH_TOKEN_KEY @"auth_token"


@implementation BKUser
+ (BOOL)login:(id)user{
    if ([self currentUser]) {
    }
    BOOL f = [self updateLoginUserInfo:user];
    if (f) {
    }
    return f;
}
+ (BOOL)updateLoginUserInfo:(BKUser *) user{
    if (user == nil) {
        return NO;
    }
    NSString *data = [[user dict] jsonString];
    DLOG(@"%@", data);
    if (data) {
        [DBCache setValue:data forKey:MEM_USER_KEY];
        [Mem remove:MEM_USER_KEY];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_USER_PROFILT_UPDATED object:nil];
        return YES;
    }else{
        DLOG(@"error");
    }
    return NO;
}
+ (id)currentUser{
    @synchronized(self){
        id user = [Mem valueForKey:MEM_USER_KEY];
        if (!user) {
            NSDictionary *json = [[DBCache valueForKey:MEM_USER_KEY] json];
            if (json) {
                user = [[self alloc] initWithDictionary:json];
                [Mem setValue:user forKey: MEM_USER_KEY];
            }
        }
        return user;
    }
}
+ (void)loginWithAuthToken:(id)authToken{
    if(authToken){
        [DBCache setValue:authToken forKey:MEM_AUTH_TOKEN_KEY];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_USER_LOGIN object:nil];
    }
}
+ (void)logout{
    @synchronized(self){        
        [DBCache removeForKey:MEM_AUTH_TOKEN_KEY];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_USER_LOGOUT object:nil];
    }
}
+ (id)authToken{
    NSDictionary *token = [DBCache dictForKey:MEM_AUTH_TOKEN_KEY];
    return token;
}
@end
